package com.liveinstars.gateway.application.endpoint;

import com.liveinstars.gateway.business.service.DynamicRouteService;
import com.onepiece.shipelves.common.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.endpoint.web.annotation.RestControllerEndpoint;
import org.springframework.cloud.gateway.actuate.GatewayControllerEndpoint;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * @author: ting
 * @date: 2019-07-15
 */
@Component
@RestControllerEndpoint(id = "redline")
public class RedLineRouteController {

    private static final Logger log = LoggerFactory.getLogger(GatewayControllerEndpoint.class);

    @Autowired
    private DynamicRouteService dynamicRouteService;

    /**
     * 根据routerId删除路由
     * @param routerId
     * @return
     */
    @PostMapping("/delete")
    public Mono<Result> delete(String routerId) {
        Result result = new Result();
        boolean booleanResult = dynamicRouteService.deleteById("baidu-route");
        if (!booleanResult) {
            result.setCode("-100");
            result.setMessage("删除路由失败！");
        }
        return Mono.just(result);
    }


    /**
     * 获取网关所有路由
     * @return
     */
    @GetMapping("/getRouters")
    public Flux<RouteDefinition> getRouters(){
        Flux<RouteDefinition> routers = dynamicRouteService.getRouters();
        return routers;
    }

    /**
     * 添加网关路由
     * @param routeDefinition
     * @return
     */
    @PostMapping("/add")
    public Mono<Result> add(@RequestBody RouteDefinition routeDefinition){
        Result result = new Result();
        boolean booleanResult = dynamicRouteService.add(routeDefinition);
        if (!booleanResult) {
            result.setCode("-100");
            result.setMessage("添加路由失败！");
        }
        return Mono.just(result);
    }

    /**
     * 重置网关所有路由
     * @param list
     * @return
     */
    @PostMapping("/resetAll")
    public Mono<Result> resetAll(List<RouteDefinition> list) {
        Result result = new Result();
        boolean booleanResult = dynamicRouteService.updateAll(list);
        if (!booleanResult) {
            result.setCode("-100");
            result.setMessage("重置所有路由失败！");
        }
        return Mono.just(result);
    }
}
